﻿/**
* CRL
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CRL.Core
{
    /// <summary>
    /// 并发请求限制
    /// </summary>
    public class RequestLimiter
    {
        int current;
        object lockObj = new object();
        DateTime time = DateTime.Now;
        TimeSpan interval;
        int total;
        public RequestLimiter(int _total, TimeSpan _interval)
        {
            interval = _interval;
            total = _total;
            fill();
        }
        void fill()
        {
            current = total;
        }
        public int CheckLimit()
        {
            lock (lockObj)
            {
                if (DateTime.Now - time > interval)
                {
                    fill();
                    time = DateTime.Now;
                }
                if (current == 0)
                {
                    return 0;
                }
                current--;
            }
            return current + 1;
        }
        public int GetCount()
        {
            if (DateTime.Now - time > interval)
            {
                lock (lockObj)
                {
                    fill();
                }
                time = DateTime.Now;
            }
            return current;
        }
    }
}
